package core

import (
	"log"
	"fmt"
)

type Blockchain struct {
	Blocks []*Block
}

func NewBlockchain() *Blockchain{
	genesisBlock:=GenerateGenesisBlock()
	blockchain:=Blockchain{}
	blockchain.AddBlock(&genesisBlock)
	return &blockchain
}
func (bc *Blockchain) SendData(data string){
	preBlock:=bc.Blocks[len(bc.Blocks)-1]
	newBlock:=GenerateNewBlock(*preBlock,data)
	bc.AddBlock(&newBlock)
}

func (bc *Blockchain)AddBlock(newBlock *Block){
	if len(bc.Blocks)==0{
		bc.Blocks=append(bc.Blocks,newBlock)
		return
	}
	if isValidate(*newBlock,*bc.Blocks[len(bc.Blocks)-1]){
		bc.Blocks=append(bc.Blocks,newBlock)
	}else{
		log.Fatal("invalid block")
	}
}

func isValidate(newBlock Block,oldBlock Block)bool{
	if newBlock.Index-1!=oldBlock.Index{
		return false
	}
	if newBlock.PrevBlockHash!=oldBlock.Hash{
		return false
	}

	if CalculateHash(newBlock)!=newBlock.Hash{
		return false
	}
	return true
}


func (bc *Blockchain)Print(){
	for _,block:=range bc.Blocks{
		fmt.Printf("序号：%d \n",block.Index)
		fmt.Printf("上一个哈希值：%s \n",block.PrevBlockHash)
		fmt.Printf("我的哈希值：%s \n",block.Hash)
		fmt.Printf("我的数据：%s \n",block.Data)
		fmt.Printf("我的时间戳：%d \n",block.Timestamp)
		fmt.Println("=======================================================")
	}
}